import sqlite3
from flask import render_template, request, redirect, url_for, flash, session
from . import web_bp
from models import get_all_roles, get_role_permissions, create_operation_log, get_db_connection

# 角色管理
@web_bp.route('/roles')
def roles():
    if 'user_id' not in session:
        return redirect(url_for('web.login'))
    
    roles = get_all_roles()
    return render_template('roles.html', roles=roles)

# 添加角色
@web_bp.route('/roles/add', methods=['GET', 'POST'])
def add_role():
    if 'user_id' not in session:
        return redirect(url_for('web.login'))
    
    if request.method == 'POST':
        name = request.form['name']
        description = request.form['description']
        
        conn = get_db_connection()
        cursor = conn.cursor()
        try:
            cursor.execute('INSERT INTO roles (name, description) VALUES (?, ?)',
                          (name, description))
            conn.commit()
            flash('角色添加成功')
            # 记录操作日志
            create_operation_log(session['user_id'], session['username'], '添加角色', 
                                'POST', request.url, request.remote_addr, 
                                request.headers.get('User-Agent'), f'name: {name}', '成功', 0)
        except sqlite3.IntegrityError:
            flash('角色名称已存在')
            # 记录操作日志
            create_operation_log(session['user_id'], session['username'], '添加角色', 
                                'POST', request.url, request.remote_addr, 
                                request.headers.get('User-Agent'), f'name: {name}', '角色名称已存在', 0)
        finally:
            conn.close()
        
        return redirect(url_for('web.roles'))
    
    return render_template('add_role.html')

# 角色权限分配
@web_bp.route('/roles/permissions/<int:role_id>', methods=['GET', 'POST'])
def role_permissions(role_id):
    if 'user_id' not in session:
        return redirect(url_for('web.login'))
    
    conn = get_db_connection()
    cursor = conn.cursor()
    role = cursor.execute('SELECT * FROM roles WHERE id=?', (role_id,)).fetchone()
    conn.close()
    
    if not role:
        flash('角色不存在')
        return redirect(url_for('web.roles'))
    
    if request.method == 'POST':
        # 获取表单提交的权限ID列表
        selected_permission_ids = request.form.getlist('permissions')
        
        # 获取角色当前的权限
        current_permissions = get_role_permissions(role_id)
        current_permission_ids = [str(perm[0]) for perm in current_permissions]
        
        # 计算需要添加和删除的权限
        permissions_to_add = set(selected_permission_ids) - set(current_permission_ids)
        permissions_to_remove = set(current_permission_ids) - set(selected_permission_ids)
        
        conn = get_db_connection()
        cursor = conn.cursor()
        
        try:
            # 添加新权限
            for permission_id in permissions_to_add:
                cursor.execute('INSERT INTO role_permissions (role_id, permission_id) VALUES (?, ?)', 
                              (role_id, permission_id))
            
            # 删除取消的权限
            if permissions_to_remove:
                placeholders = ','.join('?' * len(permissions_to_remove))
                cursor.execute(f'DELETE FROM role_permissions WHERE role_id = ? AND permission_id IN ({placeholders})', 
                              [role_id] + list(permissions_to_remove))
            
            conn.commit()
            flash('角色权限分配成功')
            
            # 记录操作日志
            create_operation_log(session['user_id'], session['username'], '分配角色权限', 
                                'POST', request.url, request.remote_addr, 
                                request.headers.get('User-Agent'), f'role_id: {role_id}', '成功', 0)
        except Exception as e:
            conn.rollback()
            flash(f'角色权限分配失败: {str(e)}')
            # 记录操作日志
            create_operation_log(session['user_id'], session['username'], '分配角色权限', 
                                'POST', request.url, request.remote_addr, 
                                request.headers.get('User-Agent'), f'role_id: {role_id}', f'失败: {str(e)}', 0)
        finally:
            conn.close()
        
        return redirect(url_for('web.role_permissions', role_id=role_id))
    
    # GET请求 - 显示角色权限分配页面
    from models import get_all_permissions
    all_permissions = get_all_permissions()
    role_permissions = get_role_permissions(role_id)
    role_permission_ids = [perm[0] for perm in role_permissions]
    
    return render_template('role_permissions.html', role=role, all_permissions=all_permissions, 
                          role_permission_ids=role_permission_ids)